<?php
/**
 * User: b179a9
 * Date: 05.09.11
 * Time: 16:26
 */

class PaymentController extends Zend_Controller_Action
{
    /**
     * PayPal's api url.
     * @var string
     */
    private $_uri = 'https://api-3t.sandbox.paypal.com/nvp';

    /**
     * @var Lib_Flash
     */
    private $_flashMessenger = null;

    /**
     * @var Zend_Log
     */
    private $_logger = null;

    /**
     *
     * @var string
     */
    private $_redirectUrl = '/map';

    public function init()
    {
        $this->_logger = $this->getInvokeArg('bootstrap')->getResource('Log');

        if ($this->_request->isXmlHttpRequest()) {
            $this->_helper->layout()->disableLayout();
        } else {
            $this->_helper->layout()->setLayout('pirates-layout');
        }

        $this->_flashMessenger = new Lib_Flash();

    }

    public function expressAction()
    {
        $moneyCount = $this->_request->getParam('money');
        $paymentsManager = new \Managers\Payments();
        try {
            $paymentsManager->setExpressPayment($moneyCount);
        } catch (Exception $e) {
            $this->_flashMessenger->addMessage($e->getMessage(), Lib_Flash::ERROR, Lib_Flash::PRE);
            $this->_redirect('/map');
        }
    }

    public function cancelledAction()
    {

    }

    public function directAction()
    {
        $params = $this->_request->getParams();
        $form = new App_Form_Payment_Form();
        $form->populate($params);

        if($this->_request->isPost()) {
            if($form->isValid($params)) {
                $authData = Zend_Auth::getInstance()->getStorage()->read();
                $paymentsManager = new \Managers\Payments();
                try {
                    $paymentsManager->doDirectPayment($authData->id, $params);
                    $this->_flashMessenger->addMessage('Payment completed.', Lib_Flash::NOTICE, Lib_Flash::PRE);
                    $this->_redirect('/map');
                } catch(Exception $e) {
                    $this->_flashMessenger->addMessage($e->getMessage(), Lib_Flash::ERROR, Lib_Flash::POST);
                }
            } else {
                $this->_flashMessenger->addMessage('Please, check your input.', Lib_Flash::ERROR, Lib_Flash::POST);
            }
        }
        $this->view->form  = $form;
    }

    /**
     * Действие покупки внутренней валюты.
     * @return void
     */
    public function buyAction()
    {

        $authData = Zend_Auth::getInstance()->getStorage()->read();
        $usersManager = new \Managers\Users();
        $user = $usersManager->getById($authData->id);

        $this->view->user = $user;

    }

    public function completeAction()
    {
        $params = $this->_request->getParams();
        $authData = Zend_Auth::getInstance()->getStorage()->read();
        $paymentsManager = new \Managers\Payments();
        try {
            $paymentsManager->doExpressPayment($authData->id, $params);
            $this->_flashMessenger->addMessage('Payment completed.', Lib_Flash::NOTICE, Lib_Flash::PRE);
        } catch (Exception $e) {
            $this->_flashMessenger->addMessage($e->getMessage(), Lib_Flash::ERROR, Lib_Flash::PRE);
        }
        $this->_redirect('/map');

    }

    /**
     * Saves to log file and sends by email critical errors.
     * @param $message
     * @param $type
     * @return void
     */
    private function writeLog($message, $type = Zend_Log::CRIT)
    {
        $this->_logger->log($message, $type);
        \Managers\Mail::sendEmail($message, \Managers\Mail::ADMIN, 'Auto logging system.');

    }

    private function sendEmail($user_id, $map_id)
    {

        $usersManager = new \Managers\Users();
        $user = $usersManager->getById($user_id);

        $mapManager = new \Managers\Map();
        $map = $mapManager->getById($map_id);

        $baseUrl = Zend_Controller_Front::getInstance()->getBaseUrl();
        $url = $baseUrl . 'solve/' . $map['id'];
        $text = <<<_END
        Thank you for purchasing the map. Here is your url:
        <a href="{$url}">{$url} </a>

        <a href="{$baseUrl}" > TreasureAce.com </a>
_END;
        \Managers\Mail::sendEmail($text, $user['email'], 'Thank you for purchasing.');
    }

}
